import React, {Component} from 'react';
import './index.less';
import {base, promptBox, high,toast,output} from 'nc-lightapp-front';
import setButtonStatus from "../../container/functions/setButtonStatus";
import saveDisputedInfo from "../AddNew/functions/saveDisputedInfo";
import ReferSearch from "../../../../../hrpub/common/components/referSearch/org";
import handlePK from "../../container/functions/handlePK";
import handleAllpks from "../../container/functions/handleAllpks";
import updateButtonStatus from "../../container/functions/updateButtonStatus";
import deleteDisputedData from "../../container/functions/deleteDisputedData";
import do_print from "../../../../../hrpub/common/utils/print";
import templatePrint from "../../container/functions/templatePrint";
import Export from "../../../../../hrpub/common/utils/exportHtml";
import NCBackBtn from 'src/hrpub/common/components/hr-back';
import editDisputedAction from '../../container/functions/editDisputedAction';


// const {NCBackBtn} = base;

class Header extends Component {
    constructor(props) {
        super(props);
        this.state = {printData: {}};
        this.updateOrgValue = this.updateOrgValue.bind(this);
        this.onBtnOperation = this.onBtnOperation.bind(this);
        this.goBack = this.goBack.bind(this);
        this.setPrePage = this.setPrePage.bind(this);
        this.previousPage = '';
    }

    setPrePage(value) {
        this.previousPage = value;
    }

    updateOrgValue(value) {
        this.props.updateOrgValue(value);
    }

    setButtonStatus(value) {
        setButtonStatus.call(this);
    }

    onChangeHandle(type) {
        return (value) => {
            this.props.updateState({
                [type]: value
            }, () => {
                if (this.props.hasSearched) {
                    this.props.getMainTableData();
                }
            });
        }
    }

    onBtnOperation(props, btncode, areacode, opt,page) {
        const { getMainTableData,json,editTable, form} = this.props;
        switch (btncode) {
            case 'newAdd':
                this.props.updateState({
                    page: 'add'
                }, () => {
                    setButtonStatus.call(this, 'add');
                    this.props.initCardForm();
                });
                break;
            case 'query':
                //setQueryMeta.call(this);
                let { orgVal } = this.props;
                this.props.search.openAdvSearch('search', true, ()=>{
                    let meta = this.props.meta.getMeta();
                    let items = meta.search.items;
                    items.length > 0 && items.map((item,index)=>{
                        if(item.attrcode === 'pk_psnjob.pk_dept'){
                            item.queryCondition = {
                                pk_hrorg: orgVal.refpk
                            }
                        }else if( item.attrcode === 'pk_psnjob.pk_psndoc.code' ){
                            item.queryCondition = {
                                pk_org: orgVal.refpk,
                                busiregionEnum: "psnpact",
                                GridRefActionExt: "nccloud.web.hrcm.pub.sqlbuilder.PsndocQryRefSqlBuilder"
                            }
                        }
                    })
                    this.props.meta.setMeta(meta);
                });
                break;
            case 'refresh':
                if (page === 'main'){
                    getMainTableData.call(
                        toast({
                            color: 'success',
                            content: json['cm6011-000006']/* 国际化处理： 刷新成功*/
                        })
                    );
                }else {
                    this.props.initCardForm.call(
                        toast({
                            color: 'success',
                            content: json['cm6011-000006']/* 国际化处理： 刷新成功*/
                        })
                    );
                }

                break;
            case 'cancel':
                promptBox(
                    {
                        color: "warning",
                        title: json['cm6011-000030'], /* 国际化处理： 提示*/
                        content: json['cm6011-000001'], /* 国际化处理： 是否确认要取消？*/
                        beSureBtnName: json['cm6011-000057']/*国际化处理：是*/,
                        cancelBtnName: json['cm6011-000058']/*国际化处理：否*/,
                        beSureBtnClick: function () {
                            opt.props.updateState({
                                page: 'detail'
                            }, () => {
                                setButtonStatus.call(opt, 'afterSave');
                                opt.props.initCardForm();
                            });
                        }
                    });
                break;
            case 'save':
                saveDisputedInfo.call(this,() => {
                    this.props.updateState({
                        page: 'detail'
                    }, () => {
                        setButtonStatus.call(this, 'afterSave',this.state.orgVal);
                        this.props.initCardForm();
                    });
                });
                break;
            case 'saveAdd':
                saveDisputedInfo.call(this,() => {
                    setButtonStatus.call(this, 'add');
                    this.props.initCardForm('saveAdd');
                });
                break;
            case 'delete':
                if (page === 'main'){
                    deleteDisputedData.call(this, () => {
                        const checkedData = this.props.editTable.getClickRowIndex('disputedlist') || [];
                        this.props.editTable.deleteTableRowsByRowId('disputedlist',checkedData.record.rowid);
                        handleAllpks.remove(handlePK.get());
                        console.log('handleAllpks')
                        console.log(handleAllpks.get())
                        handlePK.remove();
                    });
                    break;
                }
                deleteDisputedData.call(this, () => {
                    let nowPK = handlePK.get();
                    // let nextPK = this.props.cardPagination.getNextCardPaginationId ({id:nowPK,status:1});
                    let nextPK = handleAllpks.getNextPk(nowPK);
                    // handleAllpks.remove(nowPK);
                    if (!nextPK || handleAllpks.get().indexOf(nextPK) < 0) {
                        let allpks = handleAllpks.get()
                        if (allpks.length === 1 && allpks[0] === nowPK) {
                            nextPK = null;
                            handleAllpks.remove(nowPK);
                        } else if (allpks.length > 1) {
                            let index = allpks.indexOf(nowPK);
                            if (index == allpks.length - 1) { //是最后一条
                                nextPK = allpks[allpks.length - 2]
                            } else { //不是最后一条
                                nextPK = allpks[index + 1]
                            }
                        }
                        this.props.cardPagination.setCardPaginationId({id:nextPK,status:1});
                    }
                    handlePK.set(nextPK);
                    // if (nextPK && handleAllpks.get().indexOf(nextPK) > 0) {
                    if (!!nextPK) {
                        this.props.initCardForm();
                        handleAllpks.remove(nowPK);
                    } else{
                        form.EmptyAllFormValue('detail');
                        this.props.button.setButtonDisabled({
                            edit: true,
                            delete: true
                        });
                    }
                    // else {
                    //     this.goBack()
                    // }


                    // if(nextPK && handleAllpks.indexOf(nextPK) > 0){
                    //     this.props.initCardForm();
                    // }else{
                    //    this.goBack()
                    // }
                });
                break;
            case 'print':
                const el = document.querySelector('.main-table').cloneNode(true);
                const table = el.querySelector('.u-table-content');
                table.removeChild(table.lastElementChild);
                const tHeader = el.querySelector('.u-table-header');
                const tr = tHeader.querySelector('tr');
                tr.removeChild(tr.firstElementChild);
                tr.removeChild(tr.lastElementChild);
                let allTableList = this.props.editTable.getAllRows('disputedlist');
                let template = this.props.meta.getMeta()['disputedlist'];
                allTableList.map((item) => {
                    if(item.values.iscomposesolve.value){
                        item.values.iscomposesolve.value = json['cm6011-000057']
                    }else{
                        item.values.iscomposesolve.value = json['cm6011-000058']
                    }
                    if(item.values.isintercesolve.value){
                        item.values.isintercesolve.value = json['cm6011-000057']
                    }else{
                        item.values.isintercesolve.value = json['cm6011-000058']
                    }
                    if(item.values.isclawsolve.value){
                        item.values.isclawsolve.value = json['cm6011-000057']
                    }else{
                        item.values.isclawsolve.value = json['cm6011-000058']
                    }
                })
                do_print(
                    el,
                    {
                        title: json['cm6011-000111'] /* 国际化处理： 劳动争议*/,
                        maker: json['cm6011-000033'] /* 国际化处理： 打印人*/,
                        date: json['cm6011-000034'] /* 国际化处理： 打印日期*/,
                        beforeAppend: (data) => {
                            delete data[1];
                            return data;
                        }
                    },
                    {
                        tableTmp: template,
                        data: allTableList
                    }
                );
                break;
            case 'output':
                // 点击输出按钮
                Export(document.querySelector('.u-table-scroll'),
                    {
                        title:json['cm6011-000111'] /* 国际化处理： 劳动争议*/,
                        fileName:json['cm6011-000131'] /* 国际化处理： 劳动争议数据*/,
                        maker: json['cm6011-000100'] /* 国际化处理： 制单人*/,
                        date: json['cm6011-000101'] /* 国际化处理： 制表日期*/
                    },{
                        data: this.props.editTable.getAllData('disputedlist').rows,
                        meta : this.props.meta.getMeta()['disputedlist'],
                        showIndex: false
                    });
                break;
            case 'template_output':
                // 点击输出按钮
                output({
                    url: '/nccloud/hrcm/disputed/DisputedBatchPrintAction.do',
                    data: {
                        funcode: '60110317',      //功能节点编码，即模板编码
                        appcode: '60110317',     //模板节点标识
                        oids: [handlePK.get()],    // 功能节点的数据主键
                        outputType: 'output',
                        filename: json['cm6011-000111'] // 输出文件名 劳动争议
                    },
                    callback: function () {

                    }
                });
                break;
            case 'templateprint':
                let selectData = this.props.editTable.getClickRowIndex('disputedlist') || [];
                if (selectData.length === 0) {
                    handlePK.set(this.props.editTable.getAllRows('disputedlist')[0].values.pk_workdispute.value);
                }else{
                    handlePK.set(selectData.record.values.pk_workdispute.value);
                }
                templatePrint.call(this);
                break;
            case 'template_print':
                templatePrint.call(this);
                break;
            case 'edit':
                // if (page === 'main'){
                let getFormData = this.props.form.getAllFormValue('detail');
                // handlePK.set(selectData.record.values.pk_workdispute.value)
                let pk_workdispute = getFormData.rows[0].values.pk_workdispute.value;
                // }
                editDisputedAction(this.props.orgVal,pk_workdispute,()=>{
                    this.props.updateState({
                        page: 'edit'
                    }, () => {
                        setButtonStatus.call(this, 'edit');
                        this.props.initCardForm();
                    });
                });
                
                break;
            case 'file': 
                this.fileButtonClick()
            default:
                break;
        }
    }
    //附件管理按钮事件
    fileButtonClick() {
        let formData = this.props.form.getAllFormValue('detail')
        let pk_workdispute = formData.rows[0].values.pk_workdispute.value;
        this.props.uploadRef.showUploader(pk_workdispute);
    }
    goBack() {
        let { page, json} = this.props;
        if( page === 'edit' || page === 'add'){
            promptBox(
            {
                color: "warning",
                title: json['cm6011-000030'], /* 国际化处理： 提示*/
                content: json['cm6011-000001'], /* 国际化处理： 是否确认要取消？*/
                beSureBtnName: json['cm6011-000057']/*国际化处理：是*/,
                cancelBtnName: json['cm6011-000058']/*国际化处理：否*/,
                beSureBtnClick: ()=> {
                    this.props.updateState({
                        page: 'detail'
                    }, () => {
                        setButtonStatus.call(this, 'afterSave');
                        this.props.initCardForm();
                    });
                }
            });
        }else{
            this.props.updateState({
                page: 'main'
            }, () => {
                setButtonStatus.call(this, 'main');
                this.props.getMainTableData();
            });
        }
    }

    handlePageInfoChange (props, flag) {
        console.log("flag:"+flag)
        let pks = handleAllpks.get();
        let index = 0
        let pk_workdispute = ''
        for (index; index < pks.length; index++) {
            if (pks[index] === flag) {
                pk_workdispute = pks[index]
                break;
            }
        }
        handlePK.set(pk_workdispute)
        this.props.cardPagination.setCardPaginationId({ id: pk_workdispute, status: 1 });
        this.props.initCardForm();
    }

    render() {
        const {button, orgVal, isEdit,page,cardPagination}= this.props;
        const {createCardPagination} = cardPagination;
        let pagination = createCardPagination({
            handlePageInfoChange: this.handlePageInfoChange.bind(this)
        })
        return (
            <div className="header nc-bill-header-area">
                <div className="header-refer" style={{display: page === 'main' ? '' : 'none'}}>
                    <ReferSearch
                        disabled={isEdit}
                        orgVal={orgVal}
                        getOrgData={this.updateOrgValue}
                    />
                </div>
                <div style={{display: page === 'detail' || page === 'edit' || page === 'add' ? '' : 'none'}}>
                    <NCBackBtn onClick={this.goBack}/>
                </div>
                <div className="btn-group">
                    <div className="definition-icons">
                        {button.createButtonApp({
                            area: 'head',
                            onButtonClick: (props, btncode) => {
                                this.onBtnOperation(props, btncode, 'head', this,page);
                            }
                        })}
                        <div className="cardPagination" style={{display: page === 'detail' ? '' : 'none'}}>
                            {
                                pagination
                            }
                        </div>
                    </div>
                </div>
            </div>
        );
    }
}

export default Header;
